package com.sxf.core.validator;

import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * @description: 是否是时间注解
 * @author: zhangyb@ccccit.com.cn
 * @date: 2021年2月2日 上午8:51:46
 */
public class IsDatetimeValidator implements ConstraintValidator<IsDatetime, String> {

	private String pattern;

	@Override
	public void initialize(IsDatetime constraintAnnotation) {
		this.pattern = constraintAnnotation.pattern();
	}

	@Override
	public boolean isValid(String value, ConstraintValidatorContext context) {
		if (StringUtils.isBlank(value)) {
			return true;
		}
		SimpleDateFormat format = new SimpleDateFormat(pattern);
		try {
			format.setLenient(false);
			format.parse(value);
		} catch (ParseException e) {
			return false;
		}

		return true;
	}

}
